import sys

from PyQt5 import QtCore
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QBrush, QColor, QIcon

from utils.KGraph import WidgetGraph
from forms.mainWindow import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication, QTableWidgetItem, QLabel, QHeaderView, \
    QMessageBox, QSizePolicy

from utils.ThreadUpdateWidget import ThreadUpdateWidget, ThreadUpdateZhWidget


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.statusLabel = QLabel()
        self.widgetGraph = WidgetGraph()
        self.timerUpdateWindow = QTimer()
        self.setupUi(self)
        self.threadUpdateWidget = ThreadUpdateWidget(self)
        self.threadUpdateZhWidget = ThreadUpdateZhWidget(self)
        self.initConnection()

        self.btnSelectStock.click()
        self.timerUpdateWindow.start()

    def setupUi(self, MainWindow):
        super().setupUi(self)
        self.progressBar.hide()
        self.setMinimumSize(1600, 904)
        self.setMaximumSize(1600, 904)
        self.setWindowIcon(QIcon("./icons/stock.ico"))

        # 右下角状态栏显示文字
        self.statusbar.addPermanentWidget(self.statusLabel)

        self.widgetGraph.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.tabWidget.setCurrentIndex(0)
        self.tabWidget.setTabText(0, '行情数据')
        self.tabWidget.setTabText(1, '自选股票')

        self.timerUpdateWindow.setInterval(3000)

    def initConnection(self):
        self.threadUpdateWidget.signalSetStockWidget.connect(self.slotSetStockWidget)
        self.threadUpdateWidget.signalAddStockToWidget.connect(self.slotAddStockToWidget)
        self.threadUpdateWidget.signalUpdateProgressBar.connect(self.progressBar.setValue)
        self.threadUpdateWidget.signalShowPermMessage.connect(self.statusLabel.setText)
        self.threadUpdateWidget.signalWidgetRowChangeColor.connect(self.slotSetStockWidgetRowColor)

        self.threadUpdateWidget.finished.connect(self.on_threadUpdateWidget_finished)

        self.widgetGraph.signalUpdateProgressBar.connect(self.progressBar.setValue)
        self.widgetGraph.signalFinished.connect(self.progressBar.hide)
        self.widgetGraph.signalShowProgressBar.connect(self.progressBar.show)

        self.timerUpdateWindow.timeout.connect(self.threadUpdateZhWidget.start)
        self.threadUpdateZhWidget.signalUpdateWindow.connect(self.slot_update_window)

    @QtCore.pyqtSlot()
    def on_threadUpdateWidget_finished(self):
        self.progressBar.hide()
        self.btnSelectStock.setEnabled(True)
        if self.threadUpdateWidget.update:
            self.statusbar.showMessage(self.tabWidget.tabText(0) + '获取完毕，共' + str(self.threadUpdateWidget.stockDF.shape[0]) + '条数据')

    @QtCore.pyqtSlot(list)
    def slot_update_window(self, data):
        self.labelStockName.setText(data[0]['f14'])
        self.labelNum.setText(f"{data[0]['f4'] / 100:.2f}")
        self.labelFloat.setText(f"{data[0]['f3'] / 100:.2f}%")
        if data[0]['f4'] < 0:
            self.labelNum.setStyleSheet('color:green')
            self.labelPrice.setStyleSheet('color:green')
            self.labelFloat.setStyleSheet('color:green')
            self.labelPrice.setText(f"{data[0]['f2']/100:.2f}↓")
        else:
            self.labelNum.setStyleSheet('color:red')
            self.labelPrice.setStyleSheet('color:red')
            self.labelFloat.setStyleSheet('color:red')
            self.labelPrice.setText(f"{data[0]['f2']/100:.2f}↑")

        self.labelStockName_2.setText(data[1]['f14'])
        self.labelNum_2.setText(f"{data[1]['f4'] / 100:.2f}")
        self.labelFloat_2.setText(f"{data[1]['f3'] / 100:.2f}%")
        self.labelPrice_2.setText(str(data[1]['f2']))
        if data[1]['f4'] < 0:
            self.labelNum_2.setStyleSheet('color:green')
            self.labelPrice_2.setStyleSheet('color:green')
            self.labelFloat_2.setStyleSheet('color:green')
            self.labelPrice_2.setText(f"{data[1]['f2']/100:.2f}↓")
        else:
            self.labelNum_2.setStyleSheet('color:red')
            self.labelPrice_2.setStyleSheet('color:red')
            self.labelFloat_2.setStyleSheet('color:red')
            self.labelPrice_2.setText(f"{data[1]['f2']/100:.2f}↑")

    @QtCore.pyqtSlot()
    def on_btnSelectStock_clicked(self):
        if self.cbStocks.currentIndex() == 0:
            self.statusbar.showMessage('正在获取：' + self.cbStocks.currentText())

            # update = True代表从网上更新本地数据，由于是第一次查询所以需要更新本地缓存数据
            self.threadUpdateWidget.update = True
            # 当前页，每次查询会将当前页置为第一页
            self.threadUpdateWidget.curPage = 0

            # 显示进度条
            self.progressBar.show()
            self.progressBar.setValue(0)
            self.tableWidgetStocks.clearContents()
            self.btnSelectStock.setDisabled(True)

            # 开始一个线程，将数据依次显示到表格
            self.threadUpdateWidget.start()

    @QtCore.pyqtSlot()
    def on_btnPrePage_clicked(self):
        if self.threadUpdateWidget.curPage > 0:
            # 如果正在更新数据，则中断原线程
            if self.threadUpdateWidget.isRunning():
                self.threadUpdateWidget.requestInterruption()

            # 等待原线程关闭
            self.threadUpdateWidget.wait()

            # 清除表格数据，将当前页码减一
            self.tableWidgetStocks.clearContents()
            self.threadUpdateWidget.curPage -= 1
            # 不从网页下载，直接使用本地缓存
            self.threadUpdateWidget.update = False
            # 开启线程更新界面
            self.threadUpdateWidget.start()

    @QtCore.pyqtSlot()
    def on_btnNextPage_clicked(self):
        if self.threadUpdateWidget.curPage < self.threadUpdateWidget.maxPage - 1:
            if self.threadUpdateWidget.isRunning():
                self.threadUpdateWidget.requestInterruption()

            self.threadUpdateWidget.wait()

            self.tableWidgetStocks.clearContents()
            self.threadUpdateWidget.curPage += 1
            self.threadUpdateWidget.update = False

            self.threadUpdateWidget.start()

    def queryAndShowStockGraph(self, code: str, name: str = ""):
        self.widgetGraph.code = code
        self.widgetGraph.name = name
        # 通过akshare接口获取股票历史行情信息
        if self.widgetGraph.query_slot(code):
            # 将单选按钮选中近一年，因为默认查询近一年
            self.widgetGraph.radioBtn1y.setChecked(True)
            self.statusbar.showMessage("查询成功！", 2000)
            self.widgetGraph.show()
        else:
            QMessageBox.warning(self, '查询失败', '查询失败，请查看控制台报错信息！')

    @QtCore.pyqtSlot(int, int)
    def on_tableWidgetStocks_cellDoubleClicked(self, i: int, j: int):
        # 获取当前行所代表的股票的代码和名称
        code = self.tableWidgetStocks.item(i, 0).text()
        name = self.tableWidgetStocks.item(i, 1).text()
        self.queryAndShowStockGraph(code, name)

    @QtCore.pyqtSlot(int, int)
    def on_tableWidgetSelfSelect_cellDoubleClicked(self, i: int, j: int):
        code = self.tableWidgetSelfSelect.item(i, 0).text()
        name = self.tableWidgetSelfSelect.item(i, 1).text()
        self.queryAndShowStockGraph(code, name)

    @QtCore.pyqtSlot()
    def on_btnAddSelfSelect_clicked(self):
        """
        用户点击加自选按钮
        :return:
        """
        row = self.tableWidgetStocks.currentRow()
        if row >= 0:
            # 获取用户选择的股票代码
            code = self.tableWidgetStocks.item(row, 0).text()
            # 如果该股票在自选表格中，则报错
            for i in range(self.tableWidgetSelfSelect.rowCount()):
                if self.tableWidgetSelfSelect.item(i, 0).text() == code:
                    QMessageBox.information(self, '重复添加', '您已添加过该股票！')
                    return

            # 要写入到自选表格的行号
            new_row = self.tableWidgetSelfSelect.rowCount()
            col_count = self.tableWidgetStocks.columnCount()
            # 自选表格行数加一
            self.tableWidgetSelfSelect.setRowCount(new_row + 1)
            self.tableWidgetSelfSelect.setColumnCount(col_count)

            if new_row == 0:
                # 设置自选表格的表头
                header_labels = [self.tableWidgetStocks.horizontalHeaderItem(i).text() for i in range(col_count)]
                self.tableWidgetSelfSelect.setHorizontalHeaderLabels(header_labels)

            # 将股票添加到自选表格
            for j in range(col_count):
                self.tableWidgetSelfSelect.setItem(new_row, j,
                                                   QTableWidgetItem(self.tableWidgetStocks.item(row, j).text()))
                self.tableWidgetStocks.item(row, j).setBackground(QBrush(QColor('#00ae9d')))

            # 将该股票添加到自选列表
            self.threadUpdateWidget.selfSelect.append(self.tableWidgetStocks.item(row, 0).text())
        self.statusbar.showMessage('添加自选成功！', 2000)

    @QtCore.pyqtSlot()
    def on_btnRemoveSelfSelect_clicked(self):
        row = self.tableWidgetSelfSelect.currentRow()
        if row >= 0:
            code = self.tableWidgetSelfSelect.item(row, 0).text()
            name = self.tableWidgetSelfSelect.item(row, 1).text()
            # 从列表中删除
            self.threadUpdateWidget.selfSelect.remove(code)
            # 从自选列表中删除
            self.tableWidgetSelfSelect.removeRow(row)
            # 刷新股票表格，更新股票行颜色
            self.threadUpdateWidget.start()
            self.statusbar.showMessage(f'移除自选：代码：{code}，名称：{name}')

    @QtCore.pyqtSlot(int, int, str)
    def slotAddStockToWidget(self, i: int, j: int, text: str):
        self.tableWidgetStocks.setItem(i, j, QTableWidgetItem(text))

    @QtCore.pyqtSlot(int, int, list)
    def slotSetStockWidget(self, row_count: int, col_count: int, labels: list):
        self.tableWidgetStocks.setRowCount(row_count)
        self.tableWidgetStocks.setColumnCount(col_count)
        self.tableWidgetStocks.setHorizontalHeaderLabels(labels)
        self.tableWidgetStocks.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)

    @QtCore.pyqtSlot(int, str)
    def slotSetStockWidgetRowColor(self, row, color):
        try:
            col_cnt = self.tableWidgetStocks.columnCount()
            brush = QBrush(QColor(color))
            for j in range(col_cnt):
                self.tableWidgetStocks.item(row, j).setBackground(brush)
        except AttributeError as e:
            print(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())
